/*
* showshow:
* Just show picture and text posted by weixin on PC , because the company don't allow to use weixin in computer.
*
*/

var express = require('express');
var wechat = require('wechat');
var path = require('path');
var fs = require('fs');
var url = require('url');
var download = require('download');
var app = express();

// wechat
var config = {
  token: 'pengloo53'
};

app.use(express.static(path.join(__dirname, '.data/dist/')));

app.get('/user/:id', function(req,res,next){
  var pathname = url.parse(req.url).pathname;
  var match = pathname.match(/^\/user\/(.+)/);
  if (match){
    var username = match[1];
    var file = path.join(process.cwd(), '/.data/' , username);
    var pageContent = '';
    initData(file,function(result){
      for(var i = result.length -1 ; i >= 0 ; i--){
        var dateDisplay = new Date(result[i].CreateTime * 1);
        var text = result[i].text;
        var image = result[i].image;
        pageContent += '<h2>' + dateDisplay.toLocaleString() + '</h2>';
        if(text){
          pageContent += '<p>' + text + '</p>';
        }else{
          pageContent += '<p><a href="/'+ result[i].image +'"><img src="/'+ result[i].image +'" width="600px"></a></p>';
        }
        pageContent += '<hr/>';
      }
      res.send(pageContent);
    });
  }
});

app.use('/', wechat(config, function(req,res,next){
  var message = req.weixin;
  console.log(message);
  var FromUserName = message.FromUserName;
  var CreateTime = new Date().getTime();
  var file = path.join(process.cwd(), '/.data/.', FromUserName);
  var data = {};

  // 每一条信息保存时间，字段为CreateTime
  data.CreateTime = CreateTime;

  switch (message.MsgType){
    case 'text':
      var Content = message.Content;
      data.text = Content;  // 当为文本内容的时候，保存text字段
      storeData(file,data,function(result){
        if(result == 'success'){
          res.reply("请在浏览器中访问：http://pengloo53.eicp.net/user/" + FromUserName);
        }else{
          res.reply(result);
        }
      });
      break;
    case 'image':
      var PicUrl = message.PicUrl;
      var picName = new Date().getTime() + '.png';
      var imagePath = path.join(process.cwd(), '/.data/dist/' , picName);
      data.image = picName; // 当为图片内容的时候，保存image字段（时间戳命名）
      downloadPic(PicUrl, imagePath ,function(result){
        if(result == 'success'){
          storeData(file,data,function(result){
            if(result == 'success'){
              res.reply("图片上传成功，请在浏览器中访问：http://pengloo53.eicp.net/user/" + FromUserName);
            }else{
              res.reply(result);
            }
          })
        }
      });
      break;
    default:
      res.reply('欢迎使用showshow小工具，请输入文本或是图片！');
  }
}));

// 下载文件
function downloadPic(PicUrl,imagePath,callback) {
  download(PicUrl).then(data => {
    fs.writeFileSync(imagePath, data);
    callback('success');
  });
}

// 初始化数据
function initData(file,callback){
  fs.stat(file, function(err){
    if (err){
      callback([]);
    }else{
      var content = [];
      fs.readFile(file,'utf8',function(err,result){
        if(err){
          callback([]);
        }
        content = JSON.parse(result.toString() || []);
        callback(content);
      });
    }
  });
}

// 插入新的数据，保存到本地
function storeData(file, data, callback){
  initData(file,function(result){
    result.push(data);
    fs.writeFile(file, JSON.stringify(result), function(err){
      if(err){
        callback(err);
      }else{
        callback('success');
        console.log('store success.');
      }
    });
  })
}

app.listen(9090);
console.log('showshow is started @9090');